package com.kye.express.business.customer_intro.withdraw;

import android.app.Dialog;
import android.arch.lifecycle.Lifecycle;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.databinding.DataBindingUtil;
import android.os.Bundle;
import android.support.annotation.NonNull;
import android.support.v7.widget.DefaultItemAnimator;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.Toolbar;
import android.text.TextUtils;
import android.view.LayoutInflater;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.widget.Button;
import android.widget.CompoundButton;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.TextView;
import android.widget.Toast;

import com.afollestad.materialdialogs.DialogAction;
import com.afollestad.materialdialogs.MaterialDialog;
import com.bumptech.glide.Glide;
import com.fondesa.recyclerviewdivider.RecyclerViewDivider;
import com.jakewharton.rxbinding2.view.RxView;
import com.kye.base.DebounceObservableTransformer;
import com.kye.base.Logger;
import com.kye.express.R;
import com.kye.express.business.base.BaseToolbarActivity;
import com.kye.express.business.customer_intro.history.withdraw.CustomerIntroWithDrawHistoryActivity;
import com.kye.express.databinding.ActivityCustomerIntroWithdrawBinding;
import com.kye.express.databinding.DialogCustomerIntroVerificationCodeBinding;
import com.kye.express.utils.ScreenUtils;
import com.kye.express.view.KyeProgressDialog;
import com.kye.express.view.ToastManager;
import com.kye.model.bean.customer_intro.CustomerIntroHistoryResultBean;
import com.kye.model.bean.customer_intro.GetOpenIdResultBean;
import com.kye.model.bean.customer_intro.GetVerificationCodeResultBean;
import com.kye.model.bean.customer_intro.WithdrawResultBean;
import com.scwang.smartrefresh.layout.api.RefreshLayout;
import com.scwang.smartrefresh.layout.listener.OnRefreshLoadmoreListener;

import java.util.List;
import java.util.concurrent.TimeUnit;

import io.reactivex.Flowable;
import io.reactivex.android.schedulers.AndroidSchedulers;
import io.reactivex.functions.Action;
import io.reactivex.functions.Consumer;
import io.reactivex.functions.Function;
import me.drakeet.multitype.Items;
import me.drakeet.multitype.MultiTypeAdapter;

/**
 * 提现
 */
public class CustomerIntroWithdrawActivity extends BaseToolbarActivity implements CustomerIntroWithdrawActivityContract.CustomerIntroWithdrawActivityView {
    private ActivityCustomerIntroWithdrawBinding mBinding;

    protected MultiTypeAdapter mAdapter;
    protected Items mDatas = new Items();
    private Dialog mLoadingDialog;
    private DialogCustomerIntroVerificationCodeBinding mCodeDialogBinding;
    private String mWithDrawCompanys = "";

    private CustomerIntroWithdrawActivityContract.CustomerIntroWithdrawActivityViewPresenter mPresenter;

    public static void startActivity(Context context) {
        Intent intent = new Intent(context, CustomerIntroWithdrawActivity.class);
        context.startActivity(intent);
    }

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        mBinding = DataBindingUtil.setContentView(this, R.layout.activity_customer_intro_withdraw);
        mPresenter = new CustomerIntroWithdrawActivityContract.CustomerIntroWithdrawActivityViewPresenter(this);
        mPresenter.bind(this);
        setUpToolbar((Toolbar) findViewById(R.id.toolbar));
        setTitle(getString(R.string.customer_intro_withdraw));
        initView();
        initEvent();
        mPresenter.loadDatas(true, false);
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        if (mPresenter != null) {
            mPresenter.unbind();
        }
    }

    private void initView() {
        mAdapter = new MultiTypeAdapter();
        mAdapter.register(CustomerIntroHistoryResultBean.DatasBean.class, new CustomerIntroWithdrawListItemViewBinder(this, this));
        mBinding.recyclerview.setLayoutManager(new LinearLayoutManager(this));
        mBinding.recyclerview.setHasFixedSize(true);
        mBinding.recyclerview.setNestedScrollingEnabled(false);
        RecyclerViewDivider.with(this)
                .color(getResources().getColor(R.color.grey))
                .size(ScreenUtils.dp2px(this, 1))
                .hideLastDivider()
                .build()
                .addTo(mBinding.recyclerview);
        mBinding.recyclerview.setItemAnimator(new DefaultItemAnimator());
        mAdapter.setItems(mDatas);
        mBinding.recyclerview.setAdapter(mAdapter);
        mBinding.refreshLayout.setOnRefreshLoadmoreListener(new OnRefreshLoadmoreListener() {
            @Override
            public void onRefresh(RefreshLayout refreshlayout) {
                mPresenter.loadDatas(false, false);
            }

            @Override
            public void onLoadmore(RefreshLayout refreshlayout) {
                mPresenter.loadDatas(false, true);
            }

        });
    }

    private void initEvent() {
        mBinding.cbAll.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
            @Override
            public void onCheckedChanged(CompoundButton compoundButton, boolean b) {
                onAllCheckboxCheckChanged(b);
            }
        });

        RxView.clicks(mBinding.btnWithdraw)
                .compose(new DebounceObservableTransformer<>())
                .compose(this.bindToLifecycleDestroy())
                .subscribe(new Consumer<Object>() {
                    @Override
                    public void accept(Object o) throws Exception {
                        mPresenter.getOpenId();
                    }
                });
    }

    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        getMenuInflater().inflate(R.menu.menu_withdraw_history, menu);
        return true;
    }

    @Override
    public boolean onOptionsItemSelected(MenuItem item) {
        int id = item.getItemId();
        switch (id) {
            case R.id.menu_record:
                CustomerIntroWithDrawHistoryActivity.startActivity(this);
                break;
        }
        return super.onOptionsItemSelected(item);
    }

    @Override
    public void onComplete(boolean isLoadMore) {
        if (mLoadingDialog != null && mLoadingDialog.isShowing()) {
            mLoadingDialog.dismiss();
        }
        if (isLoadMore) {
            mBinding.refreshLayout.finishLoadmore();
        } else {
            mBinding.refreshLayout.finishRefresh();
        }
    }

    @Override
    public void onLoading() {
        try {
            if (mLoadingDialog == null) {
                mLoadingDialog = new KyeProgressDialog.Builder(this)
                        .build();
            }
            mLoadingDialog.show();
        } catch (Exception e) {

        }
    }

    @Override
    public void onLoaded(CustomerIntroHistoryResultBean resultDatas, boolean isLoadMore) {
        if (resultDatas != null) {
            if (resultDatas != null && resultDatas.getDatas() != null && resultDatas.getDatas().size() > 0) {
                if (!isLoadMore) {
                    mDatas.clear();
                    mDatas.addAll(resultDatas.getDatas());
                    mAdapter.notifyDataSetChanged();
                } else {
                    List<CustomerIntroHistoryResultBean.DatasBean> datas = (List<CustomerIntroHistoryResultBean.DatasBean>) mAdapter.getItems();
                    if (datas != null) {
                        int start = datas.size();
                        datas.addAll(resultDatas.getDatas());
                        mAdapter.notifyDataSetChanged();
                    }
                }
            }
        }
        checkNeedShowEmptyView();
    }

    @Override
    public void onError(String msg, boolean isLoadMore) {
        ToastManager.show(this, msg, Toast.LENGTH_SHORT);
        if (isLoadMore) {
            mBinding.refreshLayout.finishLoadmore(false);
        } else {
            mBinding.refreshLayout.finishRefresh(false);
        }
        if (mLoadingDialog != null && mLoadingDialog.isShowing()) {
            mLoadingDialog.dismiss();
        }
        checkNeedShowEmptyView();
    }

    @Override
    public void onItemCheckChanged() {
        Logger.d("onItemCheckChanged=====");
        double price = getAllPrice();
        if (price > 0) {
            mBinding.tvPrice.setText("￥" + price);
            mBinding.btnWithdraw.setEnabled(true);
        } else {
            mBinding.tvPrice.setText("￥0.00");
            mBinding.btnWithdraw.setEnabled(false);
        }
    }

    @Override
    public void onCompleteGetOpenId() {
        if (mLoadingDialog != null && mLoadingDialog.isShowing()) {
            mLoadingDialog.dismiss();
        }
    }

    @Override
    public void onLoadedGetOpenId(GetOpenIdResultBean datas) {
        if (datas != null) {
            String openId = datas.getOpenid();
            if (!TextUtils.isEmpty(openId)) {
                showVerificationCodeDialog();
            } else {
                new MaterialDialog.Builder(this)
                        .title(R.string.common_reminder)
                        .content("请关注" + "“跨越”微信公众号并进入“个人中心 - 登录”后再提现")
                        .positiveText(R.string.common_confirm)
                        .show();
            }
        }
    }

    @Override
    public void onErrorGetOpenId(String msg) {
        ToastManager.show(this, msg, Toast.LENGTH_SHORT);
        if (mLoadingDialog != null && mLoadingDialog.isShowing()) {
            mLoadingDialog.dismiss();
        }
    }

    @Override
    public void onErrorGetCode(String msg) {
        ToastManager.show(this, msg, Toast.LENGTH_SHORT);
    }

    @Override
    public void onLoadedGetCode(GetVerificationCodeResultBean datas) {
        if (mCodeDialogBinding != null && datas != null && datas.getPicture() != null) {
            Glide.with(this)
                    .load(datas.getPicture())
                    .into(mCodeDialogBinding.ivImgCode);
        }
    }

    @Override
    public void onCountDown(Long seconds) {
        if (mCodeDialogBinding != null) {
            if (mCodeDialogBinding != null) {
                countDown(seconds);
            }
        }
    }

    @Override
    public void onGotSmsVerificationCode() {
        ToastManager.show(this, R.string.customer_intro_verification_code_send_successfully, Toast.LENGTH_SHORT);
        countDown(GET_VERIFICATION_CODE_INTERVAL);
    }

    @Override
    public void onCompleteWithDraw() {
        if (mLoadingDialog != null && mLoadingDialog.isShowing()) {
            mLoadingDialog.dismiss();
        }
    }

    @Override
    public void onLoadedWithDraw(WithdrawResultBean datas) {
        if (datas != null) {
            if ("1".equals(datas.getStatus())) {
                ToastManager.show(this, R.string.customer_intro_withdraw_successfully, Toast.LENGTH_SHORT);
                setResult(RESULT_OK,new Intent());
                finish();
            } else {
                String msg = datas.getRetMsg();
                if (TextUtils.isEmpty(msg)) {
                    msg = getString(R.string.customer_intro_withdraw_failed);
                }
                ToastManager.show(this, msg, Toast.LENGTH_SHORT);
            }
        }
    }

    @Override
    public void onErrorWithDraw(String msg) {
        ToastManager.show(this, msg, Toast.LENGTH_SHORT);
        if (mLoadingDialog != null && mLoadingDialog.isShowing()) {
            mLoadingDialog.dismiss();
        }
    }

    private void checkNeedShowEmptyView() {
        List<CustomerIntroHistoryResultBean.DatasBean> datas = (List<CustomerIntroHistoryResultBean.DatasBean>) mAdapter.getItems();
        if (datas != null && datas.size() > 0) {
            mBinding.statusLayout.showContentView();
        } else {
            mBinding.statusLayout.showEmptyView();
        }
    }

    private double getAllPrice() {
        List<CustomerIntroHistoryResultBean.DatasBean> datas = (List<CustomerIntroHistoryResultBean.DatasBean>) mAdapter.getItems();
        double totalPrice = 0;
        mWithDrawCompanys = "";
        StringBuilder sb = new StringBuilder();
        if (datas != null && datas.size() > 0) {
            for (CustomerIntroHistoryResultBean.DatasBean item : datas) {
                if (item.isChecked()) {
                    totalPrice += item.getCashAmount();
                    sb.append(item.getIntroductionToCompany()).append(",");
                }
            }
            if (sb.length() > 0) {
                mWithDrawCompanys = sb.replace(sb.lastIndexOf(","), sb.length(), "").toString();
            }
        }
        return totalPrice;
    }

    private void onAllCheckboxCheckChanged(boolean checked) {
        List<CustomerIntroHistoryResultBean.DatasBean> datas = (List<CustomerIntroHistoryResultBean.DatasBean>) mAdapter.getItems();
        if (datas != null && datas.size() > 0) {
            for (CustomerIntroHistoryResultBean.DatasBean item : datas) {
                item.setChecked(checked);
            }
        }
        mAdapter.notifyDataSetChanged();
        onItemCheckChanged();
    }

    private void showVerificationCodeDialog() {
        LayoutInflater layoutInflater = LayoutInflater.from(this);
        View view = layoutInflater.inflate(R.layout.dialog_customer_intro_verification_code, null);
        mCodeDialogBinding = DialogCustomerIntroVerificationCodeBinding.bind(view);
        TextView tv_change = view.findViewById(R.id.tv_change);
        EditText edt_img_code = view.findViewById(R.id.edt_img_code);
        ImageView iv_img_code = view.findViewById(R.id.iv_img_code);
        EditText edt_text_code = view.findViewById(R.id.edt_text_code);
        Button btn_get_text_code = view.findViewById(R.id.btn_get_text_code);

        RxView.clicks(tv_change)
                .compose(new DebounceObservableTransformer<>())
                .compose(this.bindToLifecycleDestroy())
                .subscribe(new Consumer<Object>() {
                    @Override
                    public void accept(Object o) throws Exception {
                        mPresenter.getVerificationCode();
                    }
                });

        RxView.clicks(btn_get_text_code)
                .compose(new DebounceObservableTransformer<>())
                .compose(this.bindToLifecycleDestroy())
                .subscribe(new Consumer<Object>() {
                    @Override
                    public void accept(Object o) throws Exception {
                        String imageCode = edt_img_code.getText().toString();
                        if (TextUtils.isEmpty(imageCode)) {
                            ToastManager.show(CustomerIntroWithdrawActivity.this, R.string.customer_intro_input_image_code, Toast.LENGTH_SHORT);
                            return;
                        }
                        mPresenter.getSmsVerificationCode(imageCode);
                    }
                });
        MaterialDialog dialog = new MaterialDialog.Builder(this)
                .customView(view, false)
                .positiveText(R.string.common_confirm)
                .negativeText(R.string.common_cancel)
                .onPositive(null)
                .dismissListener(new DialogInterface.OnDismissListener() {
                    @Override
                    public void onDismiss(DialogInterface dialogInterface) {
                        mCodeDialogBinding = null;
                    }
                })
                .show();
        dialog.getActionButton(DialogAction.POSITIVE).setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                String smsCode = edt_text_code.getText().toString();
                if (TextUtils.isEmpty(smsCode)) {
                    ToastManager.show(CustomerIntroWithdrawActivity.this, R.string.customer_intro_input_sms_code, Toast.LENGTH_SHORT);
                    return;
                }
                double price = getAllPrice();
                if (price > 0) {
                    mPresenter.withDraw(mWithDrawCompanys, price + "", smsCode);
                } else {
                    ToastManager.show(CustomerIntroWithdrawActivity.this, R.string.customer_intro_withdraw_price_error, Toast.LENGTH_SHORT);
                }
                dialog.dismiss();
            }
        });
        dialog.setCanceledOnTouchOutside(false);
        mPresenter.getVerificationCode();
        mPresenter.checkNeedCountDown();
    }

    private void countDown(final Long seconds) {
        Flowable.interval(0, 1, TimeUnit.SECONDS)
                .take(seconds)
                .map(new Function<Long, Long>() {
                    @Override
                    public Long apply(Long aLong) throws Exception {
                        return seconds - aLong;
                    }
                })
                .compose(getProvider().<Long>bindUntilEvent(Lifecycle.Event.ON_DESTROY))
                .observeOn(AndroidSchedulers.mainThread())
                .subscribe(new Consumer<Long>() {
                    @Override
                    public void accept(Long s) throws Exception {
                        if (mCodeDialogBinding != null) {
                            mCodeDialogBinding.setVerificationCodeTimer(s);
                        }
                    }
                }, new Consumer<Throwable>() {
                    @Override
                    public void accept(Throwable throwable) throws Exception {
                        if (mCodeDialogBinding != null) {
                            mCodeDialogBinding.setVerificationCodeTimer(null);
                        }
                    }
                }, new Action() {
                    @Override
                    public void run() throws Exception {
                        if (mCodeDialogBinding != null) {
                            mCodeDialogBinding.setVerificationCodeTimer(null);
                        }
                    }
                });
    }
}
